﻿#region File and License Information
/*
<File>
	<License>
		Copyright © 2009 - 2017, Daniel Vaughan. All rights reserved.
		This file is part of Calcium (http://calciumsdk.net), 
		which is released under the MIT License.
		See file /Documentation/License.txt for details.
	</License>
	<CreationDate>2013-03-21 20:07:26Z</CreationDate>
</File>
*/
#endregion

using System;

namespace Outcoder.Cloud.Azure
{
	/// <summary>
	/// Encodes text as to be Azure Notification Hub tag compatible.
	/// </summary>
	public static class NotificationHubTagEncoder
	{
		/// <summary>
		/// Azure supports notification hub tags that are composed of alphnumeric characters
		/// and a set of non-alphanumeric characters. This method encodes text as Base64 
		/// and removes those illegal characters.
		/// </summary>
		/// <param name="plainText"></param>
		/// <returns></returns>
		public static string EncodeAsNotificationTag(string plainText)
		{
			byte[] plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
			string base64Encoded = Convert.ToBase64String(plainTextBytes);
			string result = base64Encoded.Replace('/', '_').Replace('+', '-').Replace('=', ':');
			return result;
		}

		/// <summary>
		/// Decodes a tag that has been encoded as an Azure compatible tag. 
		/// </summary>
		/// <param name="tag">The tag text</param>
		/// <returns>The decoded tag that was first past to <c>EncodeAsNotificationTag</c>.</returns>
		public static string DecodeNotificationTag(string tag)
		{
			string base64Encoded = tag.Replace('_', '/').Replace('-', '+').Replace(':', '=');
			byte[] base64EncodedBytes = Convert.FromBase64String(base64Encoded);
			return System.Text.Encoding.UTF8.GetString(base64EncodedBytes, 0, base64EncodedBytes.Length);
		}
	}
}
